package com.xiaoshou.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.stereotype.Controller;

import com.xiaoshou.pojo.Files;
import com.xiaoshou.pojo.Question;
import com.xiaoshou.pojo.Questiontype;
import com.xiaoshou.pojo.User;
import com.xiaoshou.util.FileUtil;

@Controller
@Results({
		@Result(name = "uploadFileSuccess", location = "oneQuestion.action", type = "redirectAction", params = {
				"questionId", "${questionId}" }),
		@Result(name = "toUploadFile", location = "uploadfile.jsp", type = "dispatcher", params = {
				"question", "${question}", "fileTypesList", "${fileTypesList}" }),

		@Result(name = "downloadFile", type = "stream", params = {
				"contentType", "${contentType}", "inputName", "inputStream",
				"contentDisposition",
				"attachment;filename=${downloadFileName}", "bufferSize", "4096" }),
		@Result(name = "pageOfFilesPage", location = "oneFiles.jsp", type = "dispatcher", params = {
				"files", "${files}", "filename", "${filename}", "question",
				"${question}" }),
		@Result(name = "mainToFilesFF", location = "transToFile.action", type = "redirectAction", params = {
				"files", "${files}", "filename", "${filename}" }),
		@Result(name = "failOfTran", location = "oneQuestion.action", type = "redirectAction"),
		@Result(name = "deleteOneFileSuccess", location = "oneQuestion.action", type = "redirectAction", params = {
				"questionId", "${questionId}" })

})
public class FilesAction extends BaseAction {

	private static final long serialVersionUID = 1L;
	private String fileId;
	private Files files;
	private File file;
	private String filename;
	private String questionId;
	private Question question;
	private InputStream inputStream;
	private User user;
	private String filetypeId;
	private String fileFileName;

	private String downloadFileName;
	private InputStream inptInputStream;
	private String contentType;

	private List<Questiontype> questiontypesList;

	@Override
	public String execute() throws Exception {

		return null;
	}

	@Action("deleteFileInQuestionPage")
	// .action?fileId=${files.files.id}&&questionId=${question.id}
	public String deleteOneFileInQuestion() {
		System.out.println(questionId);
		getFilesService().deleteFileInQuestion(fileId);
		return "deleteOneFileSuccess";
	}

	/*
	 * @Action("transToFile") public String transToFilesPage(){ return
	 * "pageOfFilesPage"; }
	 */

	@Action("gotoPreviewPage")
	public String gotoPreviewPage() {
		if (questionId != null && !"".equals(questionId)) {
			question = getQuestionService().getQuestionDao().findById(
					questionId);
		} else {
			question = null;
		}
		files = getFilesService().getFilesDao().findById(fileId);
		// 判断文件的扩展名
		if (getFilesService().judgeUrl(files)) {
			filename = files.getFileurl().substring(
					files.getFileurl().lastIndexOf("\\"),
					files.getFileurl().length());
			// return "mainToFilesFF";
		} else {
			filename = null;
			// return "failOfTran";
		}
		return "pageOfFilesPage";
	}

	@Action("editFileName")
	public String editFileNameByUser() {
		getFilesService().updateFilesName(filename, fileId);

		return null;
	}

	@Action("thisfile")
	public String toOneFilePage() {
		files = getFilesService().getFilesDao().findById(fileId);
		return "mainToFiles";
	}

	@Action("downfile")
	public String downFileByFileId() {
		files = getFilesService().getFilesDao().findById(fileId);
		files.getFileurl();
		downloadFileName = files.getFileurl().substring(
				files.getFileurl().indexOf("files\\") + 7,
				files.getFileurl().length());
		try {
			inputStream = new FileInputStream(new File(files.getFileurl()));
			downloadFileName = new String(downloadFileName.getBytes("utf-8"),
					"ISO-8859-1");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		return "downloadFile";
	}

	@Action("uploadFile")
	public String toUploadPage() {
		question = getQuestionService().getQuestionDao().findById(questionId);
		questiontypesList = getQuestionTypeService().getQuestionTypeDao()
				.findAll();
		return "toUploadFile";
	}

	@Action("thisfileForUpload")
	public String toThisFilePage() {
		System.out.println(questionId);
		// 去库中查md5值，看是否有此文件
		List<String> list = getFilesService().getMd5List();
		if (list.contains(FileUtil.getMd5OfFile(file.getPath()))) {
			try {
				HttpServletResponse response = ServletActionContext
						.getResponse();
				response.setContentType("application/json;charset=utf-8");
				PrintWriter out = response.getWriter();
				out.print("库里已经存在该文件！");
				out.flush();
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return null;
		}
		// 后缀
		String suffix = fileFileName.substring(fileFileName.lastIndexOf("."),
				fileFileName.length());
		// 前缀
		String prefix = fileFileName
				.substring(0, fileFileName.lastIndexOf("."));

		question = getQuestionService().getQuestionDao().findById(questionId);

		filename = files.getFilename();
		String filepath = ServletActionContext.getServletContext().getRealPath(
				"/files/")
				+ "\\"
				+ filename
				+ "-" + prefix + suffix;
		files.setFileurl(filepath);

		FileUtil.copyFile(filepath, file);
		user = (User) getFromSession("user");
		getFilesService().saveFilesOfUpload(user, questionId, file, files);
		return "uploadFileSuccess";
	}

	public String getFileId() {
		return fileId;
	}

	public void setFileId(String fileId) {
		this.fileId = fileId;
	}

	public Files getFiles() {
		return files;
	}

	public void setFiles(Files files) {
		this.files = files;
	}

	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}

	public String getFilename() {
		return filename;
	}

	public void setFilename(String filename) {
		this.filename = filename;
	}

	public String getQuestionId() {
		return questionId;
	}

	public void setQuestionId(String questionId) {
		this.questionId = questionId;
	}

	public Question getQuestion() {
		return question;
	}

	public void setQuestion(Question question) {
		this.question = question;
	}

	public InputStream getInputStream() {
		return inputStream;
	}

	public void setInputStream(InputStream inputStream) {
		this.inputStream = inputStream;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public String getFiletypeId() {
		return filetypeId;
	}

	public void setFiletypeId(String filetypeId) {
		this.filetypeId = filetypeId;
	}

	public String getFileFileName() {
		return fileFileName;
	}

	public void setFileFileName(String fileFileName) {
		this.fileFileName = fileFileName;
	}

	public String getDownloadFileName() {
		return downloadFileName;
	}

	public void setDownloadFileName(String downloadFileName) {
		this.downloadFileName = downloadFileName;
	}

	public InputStream getInptInputStream() {
		return inptInputStream;
	}

	public void setInptInputStream(InputStream inptInputStream) {
		this.inptInputStream = inptInputStream;
	}

	public String getContentType() {
		return contentType;
	}

	public void setContentType(String contentType) {
		this.contentType = contentType;
	}

	public static long getSerialversionuid() {
		return serialVersionUID;
	}

	public List<Questiontype> getQuestiontypesList() {
		return questiontypesList;
	}

	public void setQuestiontypesList(List<Questiontype> questiontypesList) {
		this.questiontypesList = questiontypesList;
	}

}
